package cn.rocksolid.sport.assist.service.impl;

import cn.rocksolid.sport.assist.config.ConfigConst;
import cn.rocksolid.sport.assist.config.IdCardVerifierConfig;
import cn.rocksolid.sport.assist.entity.IdCardEntity;
import cn.rocksolid.sport.assist.idcard.AliYunIdCardVerifier;
import cn.rocksolid.sport.assist.idcard.IdCardVerifier;
import cn.rocksolid.sport.assist.service.IdCardService;
import cn.rocksolid.sport.common.Constant.IdCardVerifierType;
import cn.rocksolid.sport.common.error.RSE;
import cn.rocksolid.sport.common.error.RockSolidException;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

@Service
public class IdCardServiceImpl implements IdCardService {

  private Map<IdCardVerifierType, Map<String, IdCardVerifier>> idCardVerifiers;

  @Autowired
  public IdCardServiceImpl(IdCardVerifierConfig idCardVerifierConfig) {
    Map<IdCardVerifierType, Map<String, Map<String, String>>> verifierConfigs = idCardVerifierConfig
            .getIdCardVerifierConfigs();
    if (MapUtils.isNotEmpty(verifierConfigs)) {
      idCardVerifiers = new EnumMap<>(IdCardVerifierType.class);
      for (Map.Entry<IdCardVerifierType, Map<String, Map<String, String>>> typeOfIdCardVerifierConfigs : verifierConfigs
              .entrySet()) {
        if (IdCardVerifierType.ALIYUN == typeOfIdCardVerifierConfigs.getKey()) {
          Map<String, IdCardVerifier> aliYunIdCardVerifierProviders = new HashMap<>();
          for (Map.Entry<String, Map<String, String>> config : typeOfIdCardVerifierConfigs.getValue().entrySet()) {
            aliYunIdCardVerifierProviders.put(config.getKey(), new AliYunIdCardVerifier(config.getValue()));
          }
          idCardVerifiers.put(IdCardVerifierType.ALIYUN, aliYunIdCardVerifierProviders);
        } else {
          throw new RockSolidException(RSE.INVALID_IVP_CONF);
        }
      }
    }
  }

  @Override
  public IdCardEntity verify(String number, String name) {
    IdCardVerifier verifier = null;
    if (null == idCardVerifiers.get(IdCardVerifierType.ALIYUN)
        || null == (verifier = idCardVerifiers.get(IdCardVerifierType.ALIYUN).get(ConfigConst.DEFAULT_CONF))) {
      throw new RockSolidException(RSE.MISS_IVP);
    }
    try {
      return verifier.verify(number, name);
    } catch (Exception exp) {
      throw new RockSolidException(RSE.HTTP_COMM_ERR);
    }
  }

  @Override
  public IdCardEntity verifyWithPhoto(String number, String name, String photo) {
    IdCardVerifier verifier = null;
    if (null == idCardVerifiers.get(IdCardVerifierType.ALIYUN)
        || null == (verifier = idCardVerifiers.get(IdCardVerifierType.ALIYUN).get(ConfigConst.DEFAULT_CONF))) {
      throw new RockSolidException(RSE.MISS_IVP);
    }
    return verifier.verifyWithPhoto(number, name, photo);
  }

}
